package organization

import (
	"fmt"
	"gq_volunteer_platform/bean"
	"gq_volunteer_platform/model/admin"
	"gq_volunteer_platform/model/organization"
	ServiceAdmin "gq_volunteer_platform/service/admin"

	"github.com/lluck42/tools"
	"github.com/lluck42/tools/tree"

	"github.com/gin-gonic/gin"
)

func AllList(c *gin.Context) {

	var list []struct {
		ID   uint
		Name string
	}

	var tx = bean.MysqlDb.Model(&organization.Organization{})

	// 查询列表
	if err := tx.Order("`sort` ASC").Find(&list).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	c.PureJSON(200, gin.H{
		"list": list,
	})
}

func MyAllList(c *gin.Context) {
	var req struct {
		Name string `binding:"max=255"`
	}

	if err := c.ShouldBindQuery(&req); err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}

	var list []struct {
		ID   uint
		Name string
	}

	var tx = bean.MysqlDb.Model(&organization.Organization{})

	var organization_my_ids, err = ServiceAdmin.MyOrganizationIds(c, 0)
	if err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}

	tx.Where("`id` in ?", organization_my_ids)

	if req.Name != "" {
		tx = tx.Where("`name` like ?", "%"+req.Name+"%")
	}

	// 查询列表
	if err := tx.Order("`sort` ASC").Find(&list).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	c.PureJSON(200, gin.H{
		"list": list,
	})

}

func MyList(c *gin.Context) {
	var req struct {
		Page       int    `binding:"required,gte=1"`
		Limit      int    `binding:"required,gte=1"`
		Name       string `binding:"max=255"`
		Id         uint   `binding:"max=10000000"`
		CategoryId uint   `binding:"max=10000000"`
	}

	if err := c.ShouldBindQuery(&req); err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}

	var offset = (req.Page - 1) * req.Limit

	var organization_my_ids, err = ServiceAdmin.MyOrganizationIds(c, 0)
	if err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}

	// 查询
	var count int64
	var list []organization.Organization
	var tx = bean.MysqlDb.Model(&organization.Organization{})

	tx.Where("`id` in ?", organization_my_ids)

	if req.Name != "" {
		tx = tx.Where("`name` like ?", "%"+req.Name+"%")
	}
	if req.CategoryId != 0 {
		tx = tx.Where("`category_id`=?", req.CategoryId)
	}
	if req.Id != 0 {
		tx = tx.Where("`id`=?", req.Id)
	}

	// 查询总数
	if err := tx.Count(&count).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	// 查询列表
	if err := tx.Limit(req.Limit).Offset(offset).Order("`id` DESC").Find(&list).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	c.PureJSON(200, gin.H{
		"count": count,
		"list":  list,
	})
}

func MyTree(c *gin.Context) {

	// 获取登录用户对象
	var adm admin.Admin
	if err := adm.Get(c); err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	// 所有数据
	var listAll []tree.Node
	if err := bean.MysqlDb.Model(&organization.Organization{}).Order("`sort` ASC").Find(&listAll).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	// 获取选中节点的树
	var loopCount uint

	var tree, err = tree.TreeSelfGet(adm.OrganizationId, &listAll, &loopCount)
	if err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}

	c.PureJSON(200, tree)
}

func MyDelete(c *gin.Context) {

	var req struct {
		ID uint `binding:"max=10000000"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		bean.Log.Warning(err)
		c.String(400, err.Error())
		return
	}

	var organization_my_ids, err = ServiceAdmin.MyOrganizationIds(c, 0)
	if err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}

	if !tools.InList(organization_my_ids, req.ID) {
		var err = fmt.Sprintf("没有该组织权限id:%d", req.ID)
		bean.Log.Error(err)
		c.String(403, err)
		return
	}

	var one organization.Organization
	if err := bean.MysqlDb.Where("id=?", req.ID).First(&one).Error; err != nil {
		bean.Log.Warning(err)
		c.String(400, fmt.Sprintf("组织不存在id:%d", req.ID))
		return
	}

	if err := bean.MysqlDb.Delete(&one).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	c.String(200, "ok")
}

func MyEdit(c *gin.Context) {

	var req struct {
		ID                     uint    `binding:"max=10000000"`
		ParentId               uint    `binding:"max=10000000"`
		CategoryId             uint    `binding:"max=10000000"`
		Name                   string  `binding:"max=255"`
		Sort                   uint    `binding:"max=10000"`
		ResponsiblePerson      string  `binding:"max=255"`
		ResponsiblePersonPhone string  `binding:"max=255"`
		Address                string  `binding:"max=255"`
		Longitude              float64 `binding:"max=10000"`
		Latitude               float64 `binding:"max=10000"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		bean.Log.Warning(err)
		c.String(400, err.Error())
		return
	}

	var organization_my_ids, err = ServiceAdmin.MyOrganizationIds(c, 0)
	if err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}

	// 判断 parentId
	if !tools.InList(organization_my_ids, req.ParentId) {
		var err = fmt.Sprintf("没有该组织权限id:%d", req.ParentId)
		bean.Log.Error(err)
		c.String(403, err)
		return
	}

	var one organization.Organization
	one.ID = req.ID
	one.ParentId = req.ParentId
	one.CategoryId = req.CategoryId
	one.Name = req.Name
	one.Sort = req.Sort

	one.ResponsiblePerson = req.ResponsiblePerson
	one.ResponsiblePersonPhone = req.ResponsiblePersonPhone
	one.Address = req.Address

	one.Longitude = req.Longitude
	one.Latitude = req.Latitude

	// 保存对象
	if one.ID == 0 {
		if err := bean.MysqlDb.Create(&one).Error; err != nil {
			bean.Log.Error(err)
			c.String(500, "数据库错误")
			return
		}
	} else {
		// 验证id权限
		if !tools.InList(organization_my_ids, req.ID) {
			var err = fmt.Sprintf("没有该组织权限id:%d", req.ID)
			bean.Log.Error(err)
			c.String(403, err)
			return
		}

		if err := bean.MysqlDb.Updates(&one).Error; err != nil {
			bean.Log.Error(err)
			c.String(500, "数据库错误")
			return
		}
	}

	c.String(200, "ok")
}

func Detail(c *gin.Context) {

	var req struct {
		ID uint `binding:"max=10000000"`
	}

	if err := c.ShouldBindQuery(&req); err != nil {
		bean.Log.Warning(err)
		c.String(400, err.Error())
		return
	}

	var one organization.Organization
	if err := bean.MysqlDb.Where("id=?", req.ID).First(&one).Error; err != nil {
		bean.Log.Warning(err)
		c.String(400, fmt.Sprintf("组织不存在id:%d", req.ID))
		return
	}

	c.PureJSON(200, one)
}
